const auth = require("../auth/auth");
//在gitee中配置的token
const appToken = "antd-nuxt-springmvc-mybatis-push";
//项目根目录
const dir = "/home/server/antd-nuxt-springmvc-mybatis";
const tomcatWebapps = "/home/server/apache-tomcat-8.5.49/webapps";
const { exec, spawn } = require("child_process");

function deploySpawn() {
  let sp = spawn("yarn", ["run", "deploy"], {
    cwd: `${dir}/frontend`,
  });
  sp.stdout.on("data", (data) => {
    console.log(data.toString("utf-8"));
  });

  sp.stderr.on("data", (data) => {
    console.log("nuxt打包报错:", data.toString("utf-8"));
  });

  sp.on("exit", (data) => {
    console.log("nuxt打包完毕，状态码:", data);
    sp = null;
  });
}

function deployJava() {
  //发布后端Java部分。流程为：先打包，然后备份原始war包，然后把新打的包移动进去
  let timestamp = new Date().getTime();
  let cmd = `cd ${dir}/api;
  mvn package;
  mv ${tomcatWebapps}/api.war ${tomcatWebapps}/api.war.${timestamp};
  mv target/api.war ${tomcatWebapps};`

  console.log("开始发布java...");
  console.log("执行命令：", cmd);
  exec(
    cmd,
    {
      maxBuffer: 1024 * 2014 * 1024,
    },
    (err, stdout) => {
      if (err) {
        console.log("java发布失败，错误信息：");
        console.error(err);
      } else {
        console.log("java发布成功，信息：");
        console.log(stdout);
      }
    }
  );
}

module.exports = function (req, res) {
  console.log("收到push请求，开始处理...");
  //验证通过
  let checkAuth = auth.getCheckAuthFunc("gitee");
  if (checkAuth(req, appToken)) {
    console.log("开始发布app，请稍后...");
    //发布前端nuxt部分
    deploySpawn();
    //发布java
    deployJava();
  } else {
    console.log("验证失败");
  }

  let result = {
    msg: "finish",
  };
  res.end(JSON.stringify(result), "utf-8");
};
